import {
	deviceInfo
} from "./device";
import {
	platForm
} from "./system";
import store from "../store";
import { logoutClearStorage } from "./user_tools";
const BASE_URL = 'http://skyteksmart.com'; //"http://54.172.69.115"; //"http://192.168.10.252";//

export function request(config = {}) {
	let {
		url,
		header = {},
		method = "GET",
		data = {}
	} = config;
	url = BASE_URL + url;

	header["g-clientOs"] = 'android';//platForm();
	header["g-device"] = deviceInfo();
	if (uni.getStorageSync("token")) {
		header["g-token"] = uni.getStorageSync("token");
		const user = uni.getStorageSync('user');
		data.userId = user.userId;
	}

	console.log(url, data);
	// uni.showLoading({
	// 	title: "loading...",
	// 	mask:true
	// });
	if (config.upload) {
		header["content-type"] = "multipart/form-data";
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url, // 服务器上传接口
				filePath: data.filePath,
				name: "fileName", // 必须填写，后台用来接收文件
				formData: data,
				header,
				success: res => {
					
					const result =  JSON.parse(res.data);
					console.log("少时诵诗书",result);
					if(result.status == 0){
						resolve(result);
					}else{
						uni.showToast({
							title: "upload fail",
							icon: "none"
						})
					}
					 // 上传成功后的操作
				},
				fail: err => {
					reject(err)
					console.log("err=", err); // 上传失败后的操作
				},
				complete:res=>{
					uni.hideLoading();
				}
			});
		});
	} else {
		
		header["content-type"] = "application/x-www-form-urlencoded";
		return new Promise((resolve, reject) => {
		 let task =	uni.request({
				url,
				data,
				method,
				header,
				timeout: 10000,
				success: res => {
					console.log("res=",res.data);
					if (res.data.status === 0 || res.data.status === 6) {
						resolve(res.data)
					} else if (res.data.status === 6001) {
						uni.$emit("loginStatusChange");
						logoutClearStorage();
						uni.showToast({
							title: res.data.msg,
							icon: "none",
							success() {
								uni.reLaunch({
									url: "/pages/login/login"
								})
							}
						})
					} else {
	
						if(url.includes('/app/send/cmd2dev')){
						
							resolve(res.data)
							if (res.data.msg) {
								uni.showToast({
									title: res.data.msg,
									icon: "none"
								})
							}else{
								uni.showToast({
									title: 'server error',
									icon: "none"
								})
							}
						}else{
							if (res.data.msg) {
								uni.showToast({
									title: res.data.msg,
									icon: "none"
								})
							}else{
								uni.showToast({
									title: 'server error',
									icon: "none"
								})
							}
						}
						

					}
				},
				fail: err => {
					console.log("返回err=", err)
					reject(err)
				},
				complete: err => {
					
					uni.hideLoading();
				}

			})
		})
	}
}